package com.ruoyi.grpc;


import com.ruoyi.grpc.generate.AsrServiceGrpc;
import com.ruoyi.grpc.generate.AudioStreaming;
import com.ruoyi.handler.IflytekAsrHandler;
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

@GrpcService(interceptors = AsrInterceptor.class)
public class AsrServiceGrpcImpl extends AsrServiceGrpc.AsrServiceImplBase{

    private static final Logger log = LoggerFactory.getLogger(AsrServiceGrpcImpl.class);

    @Autowired
    private IflytekAsrHandler iflytekAsrHandler;

    @Override
    public StreamObserver<AudioStreaming.AudioFragmentRequest> send(
            StreamObserver<AudioStreaming.AudioFragmentResponse> responseObserver) {
        return new StreamObserver<AudioStreaming.AudioFragmentRequest>() {
            int index = 0;
            @Override
            public void onNext(AudioStreaming.AudioFragmentRequest audioFragmentRequest) {
                byte[] bytes = audioFragmentRequest.getAudioData().toByteArray();
                String iat = iflytekAsrHandler.iat(bytes, 0);
                if (index == 0){
                    index = 1;
                }
                log.info("识别结果{}", iat);
                log.info("服务端收到请求:'{}'", audioFragmentRequest.getSequenceNum());
                AudioStreaming.AudioFragmentResponse build = AudioStreaming.AudioFragmentResponse
                        .newBuilder()
                        .setErrorMessage("服务端：收到请求")
                        .build();
                responseObserver.onNext(build);
            }

            @Override
            public void onError(Throwable throwable) {
                log.error("服务端发生错误", throwable);
            }

            @Override
            public void onCompleted() {
                log.info("服务端完成处理");
            }
        };
    }
}
